var path = require('path')
var gulp = require('gulp')
var scss = require('gulp-sass')
var rename = require("gulp-rename")
var cleanCSS = require('gulp-clean-css')
var cssWrap = require('gulp-css-wrap')
var concat = require('gulp-concat')
var del = require('del')
var replace = require('gulp-replace');

var themeNames = ['default', 'purple']
themeNames.forEach(themeName => {
  var themeDirName = 'theme-' + themeName
  var customThemeName = '.theme-' + themeName

  gulp.task('element-' + themeName, function() {
    return gulp.src(path.resolve('./src/styles/'+themeDirName+'/element.scss'))
      .pipe(replace('~', '../../../node_modules/'))
      .pipe(rename("element_.scss"))
      .pipe(gulp.dest(path.resolve('./src/styles/'+themeDirName)))
      .pipe(scss())
      .pipe(gulp.dest(path.resolve('./theme/'+ themeDirName)))
      .pipe(cssWrap({selector:customThemeName}))
      .pipe(cleanCSS())
      .pipe(gulp.dest('./theme/' + themeDirName));
  });

  gulp.task('index-' + themeName, function() {
    return gulp.src(path.resolve('./src/styles/'+themeDirName+'/index.scss'))
      .pipe(scss())
      .pipe(gulp.dest(path.resolve('./theme/'+ themeDirName)))
      .pipe(cssWrap({selector:customThemeName}))
      .pipe(cleanCSS())
      .pipe(gulp.dest('./theme/' + themeDirName));
  });
})

gulp.task('concat-element', themeNames.map( it=> 'element-' + it), function() {
  return gulp.src('theme/**/element_.css')
    .pipe(concat('element.css'))
    .pipe(gulp.dest('src/styles/output'))
})

gulp.task('move-font', ['concat-element'], function() {
  return gulp.src(['src/styles/fonts/**'])
    .pipe(gulp.dest('src/styles/output/fonts'));
});


gulp.task('concat-index', themeNames.map( it=> 'index-' + it), function() {
  return gulp.src('theme/**/index.css')
    .pipe(concat('index.css'))
    .pipe(gulp.dest('src/styles/output'))
})

gulp.task('clean', ['move-font', 'concat-index'], function() {
  var tmp = themeNames.map(it => './src/styles/theme-'+it+'/element_.scss')
  del(['./theme', ...tmp])
})

gulp.task('default', ['clean'])
